package com.easyOrder.service.message;

/**
 * Created by liutao on 2017/7/21.
 */

import com.easyOrder.core.push.PushMessage;
import com.easyOrder.core.push.PushResult;
import com.easyOrder.dao.RequisitionDetailMapper;
import com.easyOrder.dao.UserBranchMapper;
import com.easyOrder.model.*;
import com.easyOrder.service.impl.push.IMessagePushChannel;
import com.easyOrder.service.impl.push.MessagePushTask;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;
import java.util.concurrent.ForkJoinTask;

@Service
public class MessageService {

    @Autowired
    private RequisitionDetailMapper requisitionDetailMapper;

    @Autowired
    private UserBranchMapper userBranchMapper;

    private boolean pushMessages;

    public void setPushMessages(boolean pushMessages) {
        this.pushMessages = pushMessages;
    }

    private List<IMessagePushChannel> channels;

    public List<IMessagePushChannel> getChannels() {
        return channels;
    }

    public void setChannels(List<IMessagePushChannel> channels) {
        this.channels = channels;
    }

    /**
     * 推送给餐带店管理人员
     * @param requisition
     */
    public void pushRequisitionOrderMessage(Requisition requisition){

        RequisitionDetailExample requisitionDetailExample = new RequisitionDetailExample();
        requisitionDetailExample.createCriteria().andDocumentIdEqualTo(requisition.getId());
        List<RequisitionDetail> requisitionDetails = requisitionDetailMapper.selectByExample(requisitionDetailExample);
        if(CollectionUtils.isEmpty(requisitionDetails)){
            return;
        }
        StringBuffer content = new StringBuffer(MessageFormat.format("{0}号下单成功，",requisition.getTag() ));
        requisitionDetails.forEach(requisitionDetail -> {
            content.append(MessageFormat.format("{0}{1}份，", requisitionDetail.getMaterialName(),requisitionDetail.getQuantity()));
        });
        content.append("请尽快上菜");

        UserBranchExample example = new UserBranchExample();
        example.createCriteria().andBranchIdEqualTo(requisition.getBranchId());
        List<UserBranch> userBranches = userBranchMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(userBranches)){
            userBranches.forEach(userBranch -> {
                List<ForkJoinTask<PushResult>> tasks = Lists.newArrayList();
                Long userId = userBranch.getUserId();
                PushMessage message = new PushMessage();
                message.setContent(content.toString());
                message.setDiviceId("");
                message.setAlias(userId.toString());
                channels.forEach(execute -> {
                    tasks.add(new MessagePushTask(message, execute, pushMessages).fork());
                });
            });
        }

    }
}
